package com.atguigu.com.atguigu.exer;

/**
 * 银行有一个账户。
 * 有两个住户分别向同一个账户存3000元，每次存1000，存3次。每次存完打印账户余额
 * 1.是否是多线程的问题？是，两个储户线程
 * 2.是否有共享数据？有，账户（或账户的余额）
 * 3.是否有线程安全问题？有
 * 4.需要考虑如何解决线程安全的问题？同步机制：有三种方式。
 *
 * @Description
 * @Author codingBee
 * @Date 2020/8/28/22:16
 */
class Account {
    private double balance;

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public Account(double balance) {
        this.balance = balance;
    }

    public synchronized void deposit(double amt) {
        if (amt > 0) {
            balance += amt;
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "存钱成功，余额为：" + balance);
        }
    }
}

class Customer extends Thread {
    private Account account;

    public Customer(Account account) {
        this.account = account;
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            account.deposit(1000);
        }
    }
}

public class AccountTest {
    public static void main(String[] args) {
        Account account = new Account(0);
        Customer customer1 = new Customer(account);
        Customer customer2 = new Customer(account);
        customer1.setName("甲");
        customer2.setName("乙");
        customer2.start();
        customer1.start();


    }

}
